#include "IpcServer.h"

// Qt includes
#include <QtCore/QCoreApplication>
#include <QtCore/QTextStream>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>

// Local includes
#include "traitement.h"

IpcServer::IpcServer(QObject *parent)
 : QObject(parent), mServer(0), mMainAppSocket(0), mTraitement(new Traitement)
{
	mServer = new QTcpServer(this);

	initServer();
}

void IpcServer::initServer()
{
	qDebug("init server");
	if( !mServer->listen( QHostAddress(QHostAddress::LocalHost), 666) )
	{
		QCoreApplication::exit(1);
	}

	connect(mServer, SIGNAL(newConnection()), this, SLOT(gotNewConnection()));
}

void IpcServer::gotNewConnection()
{
	qDebug("Got new connection !");

	mMainAppSocket = mServer->nextPendingConnection();

	connect(mMainAppSocket, SIGNAL(readyRead()), this, SLOT(readCommand()));
	connect(mMainAppSocket, SIGNAL(disconnected()), mMainAppSocket, SLOT(deleteLater()));
}

void IpcServer::readCommand()
{
	qDebug("readCommand()");
	QTextStream stream(mMainAppSocket);

	do
	{
		QString command;
		stream >> command;

		qDebug("read command: %s", qPrintable(command));

		if( command == QLatin1String("OPEN_MMF") )
		{
			mTraitement->openFrame();
		}
		else if( command == QLatin1String("DO_FILTER") )
		{
			mTraitement->apply();
			stream << QLatin1String("OK");
		}
		else if( command == QLatin1String("SET_BRIGHTNESS") )
		{
			int readValue=0;
			stream >> readValue;
			qDebug("Brightness value from process: %d", readValue);

			mTraitement->SetBrillanceProprety(readValue);
		}
		else if(command == QLatin1String("SET_CONTRAST"))
		{
			double readValue=0.0;
			stream >> readValue;
			//qDebug("Brightness value from process: %d", readValue);

			mTraitement->SetContrasteProprety(readValue);
		}
		else if(command == QLatin1String("SET_CONVOLUTION"))
		{
			int Convo[9];
			stream >> Convo[0] >> Convo[1] >> Convo[2] >>
					  Convo[3] >> Convo[4] >> Convo[5] >>
					  Convo[6] >> Convo[7] >> Convo[8];

			mTraitement->SetConvolutionProprety(Convo);
		}
		else if(command == QLatin1String("SET_WIDTH"))
		{
			int readValue=0;
			stream >> readValue;
			mTraitement->SetWidth(readValue);
		}
		else if(command == QLatin1String("ACTIVE_CONVO"))
		{
			int readValue=0;
			stream >> readValue;
			mTraitement->SetActiveConvo(readValue);
		}
		else if( command == QLatin1String("QUIT") )
		{
			qDebug("quit the app");
			qApp->exit(0);
		}

	}
	while( !stream.atEnd() );
}
